import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:v1/tools/srttools.dart';

import '../pojo/srtspan.dart';

// 播放器界面
// 一 中央区域
// 1. 播放区
// 2. 字幕区
// 3. 控制按键区
// 4. 用户输入区

// 二、左侧区域
// 1. 内容选择区
// 2. 信息接受

// 三、右侧区域
// 1. 内容介绍区
// 2. 字幕列表区
// 3. 生词列表区
// 4. 编辑字幕区

// 四、弹出
// 1. 查词弹出框

class PlayerScreen extends StatefulWidget {
  const PlayerScreen({super.key});

  @override
  State<PlayerScreen> createState() => _PlayerScreenState();
}

class _PlayerScreenState extends State<PlayerScreen> {
  // 播放器
  late final player = Player();
  late final controller = VideoController(player);

  // 字幕列表
  List<SrtSpan>? srts;

  // 最后位置
  Duration? lastPosition;
  // 当前字幕
  String curSubTitle = "当前字幕";
  // 当前字幕序号
  int curIndex = 0;

  // 跳转字幕模式
  bool jumpMode = false;
  DateTime? jumpDateTime;

  String lastSubTitle = "";
  DateTime blankDateTime = DateTime.now();

  int jumpAfterBlankSpanTime = 3000; // 无字幕后3秒，跳转
  int jumpCheckAfterSpanTime = 3000; // 跳转后3秒再次检测

  // 单句循环模式
  bool repeatMode = false;
  // 单句循环
  int repeatIndex = 0;

  // 键盘监听
  FocusNode focusNode = FocusNode();

  String inputSubTitle = "";
  String inputLine = "abc";
  String inputWord = "def";

  List<String> curSubTitleWords1 = <String>[];
  Map<int, bool> checkMap = {};
  List<String> curInputs = <String>[];

  @override
  void initState() {
    super.initState();

    player.stream.position.listen((Duration position) {
      if (lastPosition != null) {
        if ((lastPosition!.inMilliseconds - position.inMilliseconds).abs() <
            100) {
          return;
        }
      }
      lastPosition = position;
      // print("lastPosition=${lastPosition}");
      curSubTitle = findSubtitles(position.inMilliseconds);

      if (repeatMode) {
        // 超出范围，要跳转到开头
        if (position.inMilliseconds > srts![repeatIndex].endTime! + 500) {
          player.seek(Duration(milliseconds: srts![repeatIndex].startTime!));
        }
      } else if (jumpMode) {
        if (curSubTitle == "") {
          if (lastSubTitle != "") {
            blankDateTime = DateTime.now();
          }
          lastSubTitle = curSubTitle;

          if (DateTime.now().difference(blankDateTime).inMilliseconds >
              jumpAfterBlankSpanTime) {
            // 跳转之后的间隔
            int span = 0;
            if (jumpDateTime != null) {
              Duration d = DateTime.now().difference(jumpDateTime!);
              span = d.inMilliseconds;
              print("跳转之后的间隔:${d.inMilliseconds}ms");
            }

            if (jumpDateTime == null || span > jumpCheckAfterSpanTime) {
              // 跳转下一个
              print("curSubTitle:" + curSubTitle);
              nextSrt();
              jumpDateTime = DateTime.now();
              return;
            }
          }
        }
      }

      setState(() {
        // Update UI.
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    // FocusScope.of(context).autofocus(focusNode);
    return Column(
      children: [
        Expanded(
          child: Video(
            controller: controller,
          ),
        ),
        Container(
          height: 80,
          child: Text(
            curSubTitle,
            style: TextStyle(
                color: Colors.white,
                fontSize: 20,
                decoration: TextDecoration.none),
          ),
        ),
        Container(
          height: 50,
          child: Row(
            children: [
              IconButton(
                onPressed: () {
                  op("play_or_pause");
                },
                icon: Icon(Icons.play_arrow),
                color: Colors.grey,
              ),
              IconButton(
                onPressed: () {
                  op("prev_srt");
                },
                icon: Icon(Icons.replay),
                color: Colors.grey,
              ),
              IconButton(
                onPressed: () {
                  op("next_srt");
                },
                icon: Icon(Icons.refresh),
                color: Colors.grey,
              ),
              IconButton(
                onPressed: () {
                  op("switch_repeat");
                },
                icon: Icon(Icons.repeat_one),
                color: repeatMode ? Colors.green : Colors.grey,
              ),
              IconButton(
                onPressed: () {
                  op(
                    "switch_jump_mode",
                  );
                },
                icon: Icon(Icons.redo),
                color: jumpMode ? Colors.green : Colors.grey,
              ),
              IconButton(onPressed: foo, icon: Icon(Icons.abc)),
              IconButton(onPressed: foo, icon: Icon(Icons.call_to_action)),
              IconButton(onPressed: foo, icon: Icon(Icons.chrome_reader_mode)),
              IconButton(onPressed: foo, icon: Icon(Icons.zoom_out_map)),
              IconButton(onPressed: foo, icon: Icon(Icons.zoom_in_map)),
              IconButton(
                onPressed: () {
                  op("open_movie");
                },
                icon: Icon(Icons.file_open),
                color: Colors.grey,
              ),
              IconButton(
                onPressed: () {
                  op("open_srt");
                },
                icon: Icon(Icons.file_open_outlined),
                color: Colors.grey,
              ),
              Text(
                "${curIndex}",
                style: TextStyle(
                    color: Colors.green,
                    fontSize: 25,
                    decoration: TextDecoration.none),
              ),
              IconButton(
                  onPressed: () {
                    op("test1");
                  },
                  icon: Icon(Icons.terminal)),
              Text("重复"),
            ],
          ),
        ),
        Container(
            decoration: BoxDecoration(color: Colors.amberAccent),
            width: double.infinity,
            alignment: Alignment.center,
            height: 60,
            child: show()),
        // Container(
        //   decoration: BoxDecoration(color: Colors.deepPurpleAccent),
        //   width: double.infinity,
        //   alignment: Alignment.center,
        //   height: 60,
        //   child: Text(
        //     inputSubTitle,
        //     style:
        //         TextStyle(color: Colors.white, decoration: TextDecoration.none),
        //   ),
        // ),
        Container(
          decoration: BoxDecoration(color: Colors.lightBlueAccent),
          width: double.infinity,
          alignment: Alignment.center,
          height: 60,
          child: Text(
            inputLine,
            style:
                TextStyle(color: Colors.white, decoration: TextDecoration.none),
          ),
        ),
        KeyboardListener(
          focusNode: focusNode,
          autofocus: true, // 要开启自动焦点
          onKeyEvent: (KeyEvent event) {
            // print(event.toStringShort());
            // print(event.toStringShort());
            // print(event.deviceType);
            // print(event.character);
            // print(event.runtimeType);
            if (event.runtimeType == KeyDownEvent) {
              print(event.character);
              print(event.logicalKey.keyLabel);
              print(event.physicalKey.debugName);
              // print(event.deviceType);

              if (event.logicalKey.keyLabel == "Enter" ||
                  event.physicalKey.debugName == "Space") {
                setState(() {
                  inputLine = inputWord;
                  inputWord = "";
                  checkInputSubTitle();
                });
              } else if (event.logicalKey.keyLabel == "Backspace") {
                if (inputWord.length > 0) {
                  setState(() {
                    print(inputWord);
                    if (inputWord.length == 1) {
                      inputWord = "";
                    } else {
                      inputWord = inputWord.substring(0, inputWord.length - 2);
                    }
                    print(inputWord);
                  });
                }
              } else if (event.character != null) {
                setState(() {
                  inputWord += event.character!;
                });
              }
            }
          },
          child: Container(
            decoration: BoxDecoration(color: Colors.green),
            width: double.infinity,
            alignment: Alignment.center,
            height: 60,
            child: Text(
              inputWord,
              style: TextStyle(
                  color: Colors.white, decoration: TextDecoration.none),
            ),
          ),
        ),
      ],
    );
  }

  void foo() {}

  Future<void> op(String s) async {
    print("op");
    switch (s) {
      case "test1":
        FocusScope.of(context).requestFocus(focusNode);
        FocusScope.of(context).autofocus(focusNode);
        break;
      case "play_or_pause":
        player.playOrPause();
        break;
      case "open_movie":
        {
          FilePickerResult? result = await FilePicker.platform.pickFiles();

          if (result != null) {
            // File file = File(result.files.single.path!);
            player.open(Media(result.files.single.path!));
            print(result.files.single.path!);
          } else {
            // User canceled the picker
          }
        }
        break;
      case "open_srt":
        {
          FilePickerResult? result = await FilePicker.platform.pickFiles();

          if (result != null) {
            String filePath = result.files.single.path!;
            print("选中的文件:" + filePath);
            // 2. 读取srt文件内容
            File file = File(result.files.single.path!);
            String content = await file.readAsString();
            print("读取到内容:" + content);
            // 3. 解析srt
            srts = SrtTools.handleSrtContent(content);
            // print(srts);
            for (SrtSpan srt in srts!) {
              print(srt);
            }
          } else {
            print("用户取消了选择");
          }
        }
        break;
      case "prev_srt":
        {
          print("前一句");

          // 是否在当前句
          SrtSpan curSpan = srts![curIndex];
          if (lastPosition!.inMilliseconds > curSpan.endTime!) {
            await player.seek(Duration(milliseconds: curSpan.startTime!));
            return;
          }
          // 还在当前句，切换到前一句
          int tmpIndex = curIndex - 1;
          // curIndex = tmpIndex;
          repeatIndex--;
          initRepeat();
          if (tmpIndex < 1) return;
          if (srts == null) return;
          SrtSpan span = srts![tmpIndex];
          int startTime = span!.startTime!;
          await player.seek(Duration(milliseconds: startTime));
        }
        break;
      case "next_srt":
        nextSrt();
        break;
      case "switch_jump_mode":
        setState(() {
          jumpMode = !jumpMode;
        });

        break;
      case "switch_repeat":
        setState(() {
          repeatMode = !repeatMode;
          if (repeatMode) {
            repeatIndex = curIndex;
            initRepeat();
          }
        });
        break;
    }
  }

  Future<void> nextSrt() async {
    print("nextStr()");
    int tmpIndex = curIndex + 1;
    // curIndex = tmpIndex;
    repeatIndex++;
    initRepeat();
    print("后一句${tmpIndex}");
    if (tmpIndex >= srts!.length) return;
    if (srts == null) return;
    SrtSpan span = srts![tmpIndex];
    int startTime = span!.startTime!;
    await player.seek(Duration(milliseconds: startTime));
  }

  String findSubtitles(int ms) {
    String result = "";

    if (srts == null) return "";
    for (int i = 0; i < srts!.length; i++) {
      SrtSpan ss = srts![i];
      if (ss.startTime! < ms) {
        if (ss.endTime! > ms) {
          curIndex = i;
          return ss.content!;
        }
      } else {
        break;
      }
    }
    return result;
  }

  void initRepeat() {
    String tmp1 = srts![repeatIndex].content!;
    tmp1 = tmp1.replaceAll(",", " ");
    tmp1 = tmp1.replaceAll(".", " ");
    tmp1 = tmp1.replaceAll("<i>", "");
    tmp1 = tmp1.replaceAll("</i>", "");
    tmp1 = tmp1.replaceAll("-", "");
    tmp1 = tmp1.replaceAll("\n", " ");
    tmp1 = tmp1.replaceAll("'", "");
    tmp1 = tmp1.replaceAll("?", " ");
    tmp1 = tmp1.trim();
    // List<String> list1 = tmp1.split(" ");
    curSubTitleWords1 = tmp1.split(" ");
    checkMap = {};
    print(curSubTitleWords1);
  }

  final TextStyle textStyle1 = const TextStyle(
      // color: Colors.amberAccent,
      color: Colors.green,
      decoration: TextDecoration.none,
      decorationColor: Colors.blue);

  final TextStyle textStyle2 = const TextStyle(
    // color: Colors.black,
    color: Colors.amberAccent,
    decoration: TextDecoration.none,
  );

  final TextStyle blankStyle = const TextStyle(
      decoration: TextDecoration.none, decorationColor: Colors.blue);

  show() {
    List<TextSpan> spans = <TextSpan>[];
    for (int i = 0; i < curSubTitleWords1.length; i++) {
      TextSpan ts;
      if (checkMap[i] == true) {
        ts = TextSpan(text: curSubTitleWords1[i], style: textStyle1);
      } else {
        ts = TextSpan(text: curSubTitleWords1[i], style: textStyle2);
      }
      TextSpan ts2 = TextSpan(text: " ", style: blankStyle);
      spans.add(ts);
      spans.add(ts2);
    }
    InlineSpan span = TextSpan(children: spans);
    return Text.rich(span);
  }

  void checkInputSubTitle() {
    for (int i = 0; i < curSubTitleWords1.length; i++) {
      if (checkMap[i] == null || checkMap[i] == false) {
        String tmp = curSubTitleWords1[i];
        if (tmp.toLowerCase() == inputLine.toLowerCase()) {
          checkMap[i] = true;
          break;
        }
      }
    }

    bool ok = true;
    for (int i = 0; i < curSubTitleWords1.length; i++) {
      if (checkMap[i] == null || checkMap[i] == false) {
        ok = false;
      }
    }
    if (ok) {
      print("全部OK!!!");
      Future.delayed(Duration(milliseconds: 1000), () {
        nextSrt();
      });
    }
  }
}
